package edu.gyc.hiblog.auth;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.google.code.kaptcha.Producer;
import edu.gyc.hiblog.model.User;
import edu.gyc.hiblog.service.UserService;
import edu.gyc.hiblog.util.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Logger;

@Controller
public class AuthController {

    static Logger logger = Logger.getLogger(AuthController.class.getName());
    @Autowired
    Producer producer;

    @Autowired
    UserService userService;

    @GetMapping("/yzm.jpg")
    public void kaptcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        request.getSession().setAttribute("yzm", text);

        response.setHeader("Cache-control", "no-store,no-cache");
        response.setContentType("image/jpeg");
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "jpg", outputStream);

    }

    @GetMapping("/login")
    public String login() {
        return "auth/login";
    }

    @ResponseBody
    @PostMapping("/login")
    public Result dologin(String email, String password) {
        if (StrUtil.isEmpty(email) || StrUtil.isBlank(password)) {
            return Result.fail("邮箱或密码为空！");
        }

        UsernamePasswordToken token = new UsernamePasswordToken(email, SecureUtil.md5(password));

        try{
            SecurityUtils.getSubject().login(token);
        }catch (AuthenticationException e) {
            if (e instanceof UnknownAccountException) {
                return Result.fail("用户不存在");
            } else if (e instanceof LockedAccountException) {
                return Result.fail("用户被禁用");
            } else if (e instanceof IncorrectCredentialsException) {
                return Result.fail("密码错误");
            } else {
                return Result.fail("用户认证失败");
            }
        }
        return Result.success().action("/");
    }

    @RequestMapping("/user/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/";
    }
    @GetMapping("/reg")
    public String reg() {

        return "auth/reg";
    }


    @ResponseBody
    @PostMapping("/reg")
    public Result doreg(HttpServletRequest request, User user, String repass, String vercode) {
        String yzm = (String) request.getSession().getAttribute("yzm");
        if (!user.getPassword().equals(repass)) {
            return Result.fail("两次输入的密码不相同！");
        }
        if (vercode == null || !vercode.equalsIgnoreCase(yzm)) {
            return Result.fail("验证码错误！");

        }

        Result result = userService.reg(user);

        return result.action("/login");
    }
}
